package model.facade.persistence.mysql;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import model.facade.persistence.AbstractDBMS;

/**
 * 
 * @author Giuseppe Fusco (fusgius19@gmail.com)
 *
 */
public class MySQLDBMS extends AbstractDBMS {

	private Connection con;

	public MySQLDBMS(String host, int port, String db, String user, String password) throws SQLException, ClassNotFoundException{
		Class.forName("com.mysql.jdbc.Driver");
		String url = "jdbc:mysql://"+host+":"+port+"/"+db;
		con = DriverManager.getConnection(url, user,
				password);
	}

	public MySQLDBMS() throws IOException, SQLException, ClassNotFoundException{
		Class.forName("com.mysql.jdbc.Driver");
		BufferedReader buf = new BufferedReader(new InputStreamReader(new FileInputStream("src/model/facade/persistence/mysql/mysql.txt")));
		String url = "jdbc:mysql://"+buf.readLine()+":"+Integer.parseInt(buf.readLine())+"/"+buf.readLine();
		con = DriverManager.getConnection(url, buf.readLine(),
				buf.readLine());
		buf.close();
	}

	public Connection getConnection() {
		return con;
	}

	public ResultSet getResult(String query) throws SQLException{
		return con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)
				.executeQuery(query);
	}

	public int executeUpdate(String query) throws SQLException{
		return con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)
				.executeUpdate(query);
	}

	public PreparedStatement getPreparedStatement(String query) throws SQLException{
		return con.prepareStatement(query, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
	}

}
